import axios from 'axios'

const request = axios.create({
	timeoutErrorMessage: '链接超时...',
	timeout: 10000,
	responseType: 'json'
})

request.interceptors.request.use(config => {
	config.headers!.token = localStorage.getItem('token') || ""

	return config
}, error => {
	return Promise.reject(error)
})

request.interceptors.response.use(responce => {
	// 前后端约定状态码
	const { code } = responce.data
	switch(code) {
		case 200:
			console.log('请求数据成功！！');	
	}
	return responce
}, error => {
	// 根据http 状态码作相应
	const { status } = error.response
	switch (status) {
		case 500:
		case 501:
		case 502:
		case 503:
			console.log('服务器错误！！');
			break
		case 401:
			console.log('token 无效');
			break
		case 403:
			console.log('非法权限');
			break
		case 404:
			console.log('资源不存在');
			break
	}
	return Promise.reject(error)
})

export default request